<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "mt_user".
 *
 * @property string $id
 * @property string $code
 * @property string $sur
 * @property string $name
 * @property string $int_code
 * @property string $password
 * @property integer $grade
 * @property string $phone
 * @property string $email
 * @property integer $email_auth
 * @property string $sex
 * @property string $country
 * @property string $card_type
 * @property string $card_code
 * @property string $qq
 * @property string $address
 * @property string $draw
 * @property string $review
 * @property integer $status
 * @property integer $role
 * @property integer $register_time
 * @property integer $isproxy
 * @property integer $pid
 * @property integer $isauth
 * @property string $from
 * @property integer $crm_id
 * @property string $crm_name
 * @property string $update_at
 */


class User extends ActiveRecord  implements IdentityInterface
{
    //常量配置 - 用户状态
    const STATUS_NOTACTIVE = 0; //未激活用户
    const STATUS_ACTIVE = 1;    //已激活用户
    const STATUS_FREEZE = 2;    //已冻结用户
    const STATUS_DELETED = 3;   //已删除用户

    //常量配置 - 用户类型
    const REAL_ROLE = 1;        //真实用户
    const MONI_ROLE = 2;        //模拟用户

    //常量配置 - 用户等级
    const NO_PAY   = 1;         //未注资
    const LOWER_MEMBER  = 2;    //初级会员
    const HIGHER_MEMBER = 3;    //高级会员
    const BEST_MEMBER   = 4;    //至尊会员

    public static function getMemberText($grade)
    {
        switch($grade){
            case self::NO_PAY:
                return '未注资';
                break;
            case self::LOWER_MEMBER:
                return '初级会员';
                break;
            case self::HIGHER_MEMBER:
                return '高级会员';
                break;
            case self::BEST_MEMBER:
                return '至尊会员';
                break;
        }
    }


    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tb_user';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id','code','status','firm_id','avatar','name','password','rankpassword','phone','email','sex','int_code','int_id','account_type','country','pid','from','grade'],'safe'],
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED, self::STATUS_FREEZE]],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'code' => 'Code',
            'sur' => 'Sur',
            'name' => 'Name',
            'cnname' => 'Cnname',
            'password' => 'Password',
            'grade' => 'Grade',
            'phone' => 'Phone',
            'email' => 'Email',
            'email_auth' => 'Email Auth',
            'sex' => 'Sex',
            'country' => 'Country',
            'card_type' => 'Card Type',
            'card_code' => 'Card Code',
            'qq' => 'Qq',
            'address' => 'Address',
            'draw' => 'Draw',
            'review' => 'Review',
            'status' => 'Status',
            'role' => 'Role',
            'register_time' => 'Register Time',
            'isproxy' => 'Isproxy',
            'pid' => 'Pid',
            'isauth' => 'Isauth',
            'from' => 'From',
            'crm_id' => 'Crm ID',
            'crm_name' => 'Crm Name',
            'update_at' => 'Update At',
        ];
    }

    //字段的特殊处理方法
    public function fields()
    {
        //只有post的时候才处理字段数据  其他的时候按原来的数据来处理
//        if (Yii::$app->getRequest()->getIsPost()) {
//            return [
//                "region_name" => function ()
//                {
//                    $post = Yii::$app->getRequest()->post();
//                    return "techqing_".$post['Region']['region_name'] ;
//                },
//                "pingyin" => function ()
//                {
//                    $post = Yii::$app->getRequest()->post();
//                    return  "py_".$post['Region']['pid'];
//                },
//            ];
//        } else {
//            return parent::fields();
//        }

        $fields = parent::fields();

        //过滤掉一些不想显示的字段
        unset($fields['password'],$fields['code'],$fields['api_token'],$fields['updated_at']);
        return $fields;

    }


    //真实用户登陆操作
    public static function login($param)
    {
        //根据用户名判断用户是否存在
        $user = self::find()->where('phone = :phone AND status = :status AND role = :role',
            [
                ':email'=>$param['phone'],
                ':status'=>self::STATUS_ACTIVE,
                ':role'=>self::REAL_ROLE,
            ]
        )->one();

        //如果不存在,返回不存在
        if(is_null($user))
        {
            return json_encode(['code'=>'0','msg'=>'用户不存在']);
        }

        //将获取的密码加密
        $password = self::encryption($param['password'],$user['code']);

        //判断密码是否一致
        $result = self::comparepass($user['password'],$password);

        if($result)
        {
            Yii::$app->session->set('user',$user);
            return json_encode(['code'=>'1','msg'=>'登录成功']);
        }
        else
        {
            return json_encode(['code'=>'0','msg'=>'密码错误,无法登录']);
        }

    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
//    protected static function getUser()
//    {
//        if ($this->_user === null) {
//            $this->_user = User::findByUsername($this->email);
//        }
//
//        return $this->_user;
//    }

    /**
     * 根据ID获取用户名
     */
    public static function getName($uid)
    {
        $user = User::find()->where('id ='.$uid)->one();
        return $user->sur.$user->name;
    }


    /**
     * 用户密码加密
     * @param type $password
     * @param type $code
     * @return type
     */
    public static function encryption($password, $code = '')
    {
        return md5(ENCRYPTION_KEY.$password.$code);
    }


    /**
     * 生成唯一字符串
     * @return string
     */
    public static function uniqueGuid()
    {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $uuid = substr($charid, 0, 8).substr($charid, 8, 4).substr($charid, 12, 4).substr($charid, 16, 4).substr($charid, 20, 12);
        return $uuid;
    }

    /**
     * 用户密码加密
     * @param type $password
     * @param type $code
     * @return type
     */
    public static function changepass($user_id,$password)
    {
        $user = self::findIdentity($user_id);
        $user->password = $password;
        if($user->save()){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 用户密码对比
     * @param type $password
     * @param type $code
     * @return type
     */
    public static function comparepass($password,$newpassword)
    {
        if($password == $newpassword)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
//    public static function findIdentityByAccessToken($token, $type = null)
//    {
//        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
//    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        // 如果token无效的话，
        if(!static::apiTokenIsValid($token)) {
            throw new \yii\web\UnauthorizedHttpException("token过期或无效.请重新获取.");
        }

        return static::findOne(['api_token' => $token, 'status' => self::STATUS_ACTIVE]);
        // throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }


    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['phone' => $username, 'role' => self::REAL_ROLE, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->code;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        $new_password = $this->encryption($password,$this->code);
        if($new_password == $this->password)
        {
            return true;
        }else{
            return false;
        }
//       return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->code = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    /**
     * 生成 api_token
     */
    public function generateApiToken()
    {
        $this->api_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * 校验api_token是否有效
     */
    public static function apiTokenIsValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.apiTokenExpire'];
        return $timestamp + $expire >= time();
    }


    //关联UserCapital表
    public function getCapital()
    {
        return $this->hasOne(UserCapital::className(), ['uid' => 'id'])
            ->select(['uid','total']);
    }


    //表关联
    public function getAccount()
    {
        return $this->hasMany(UserAccount::className(),['uid'=>'id'])
            ->select(['uid','role','account'])
            ->where(['role'=>['1','3','4']]);
    }


    //根据pid获取所有名下真实有效客户
    public static function getUnderCustomers($pid,$role='1',$relation='')
    {
        if(empty($relation)){
            $res = self::find()->where('pid = :pid AND role = :role',array(':pid'=>$pid,':role'=>$role))->orderBy('id desc')->asArray()->all();
        }else{
            $res = self::find()->where('pid = :pid AND role = :role',array(':pid'=>$pid,':role'=>$role))->with($relation)->orderBy('id desc')->asArray()->all();
        }

        $arr = [];
        $proxys = ProxyService::getProxyList();

        //获取有效客户
        $real_customer = ProxyService::getCustomerList($pid);
        if(!$real_customer){
            $real_customer = array();
        }

       //数组重组处理
        foreach($res as $key=>$val){
            $arr[$val['id']]['id'] = $val['id'];
            $arr[$val['id']]['name'] = $val['sur'].$val['name'];
            $arr[$val['id']]['pid'] = isset($proxys[$val['pid']]['name']) ? $proxys[$val['pid']]['name'] : '';
            $arr[$val['id']]['register_time'] = date('Y-m-d',$val['register_time']);
            $arr[$val['id']]['phone'] = $val['phone'];
            $arr[$val['id']]['email'] = $val['email'];
            $arr[$val['id']]['sex'] = $val['sex'];
            $arr[$val['id']]['country'] = $val['country'];
            $arr[$val['id']]['grade'] = self::getMemberText($val['grade']);
            $arr[$val['id']]['is_real'] = !in_array($val['id'],$real_customer) ? '否' : '是';
            $arr[$val['id']]['balance'] = isset($val['capital']['total']) ? $val['capital']['total'] : '0' ;
        }

        return $arr;
    }

}
